import { useNewsStore, useOnlineUsersStore, useUserStore } from '@/stores'
const userStore = useUserStore()
const newsStore = useNewsStore()
console.log(userStore.userName)
const ws = new WebSocket(
  `ws://8.130.47.180:5173/websocket/${userStore.userName}/111`
)
ws.onopen = function () {
  console.log('WebSocket 连接已经建立。')
  console.log('群发  有人进入聊天室')
}
// 收到消息
ws.onmessage = function (event) {
  console.log('收到服务器消息：', event)
  console.log('收到服务器消息 data：')
  const dataJson = JSON.parse(event.data)
  console.log(dataJson)
  // 是对话消息,加入对话仓库
  if (dataJson.content) {
    newsStore.addNewsList(dataJson)
  } else if (dataJson.users) {
    //是在线人数的消息
    const onlineUsers = useOnlineUsersStore()
    onlineUsers.initUsers(dataJson.users)
  }
  //const res = JSON.parse(event.data)
  //console.log('解析以后的服务器消息：', res)
  console.log('群发 阿巴阿巴')
}
ws.onerror = function (event) {
  console.error('WebSocket 连接出现错误：', event)
}
ws.onclose = function () {
  console.log('群发  推出聊天室')
  console.log('WebSocket 连接已经关闭。')
}
export default ws
